package curator.lock;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/3/15.
 */
public class ZkCuratorLock {
    private static String ZK_ADDR = "localhost:2181";

    private static String LOCAK_PATH = "/lock";

    public static void main(String [] args)throws Exception{
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(10000,3);
        CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(ZK_ADDR,retryPolicy);
        curatorFramework.start();


        InterProcessMutex lock =new InterProcessMutex(curatorFramework,LOCAK_PATH);

        System.out.println("-----------开始锁-------------");
        lock.acquire();
        System.out.println("-----------锁中-------------");
        Thread.sleep(100000);
        System.out.println("-----------结束锁-------------");

        lock.release();
    }
}
